"""
通过pymysql查询table
结果处理成json
"""

import json
import sys
from mysql_utils import *

class selectTable:

    def __init__(self):
        pass
    """
       -sql : 传入sql查询
       -isCamel : 列名是否使用驼峰，默认使用
    """
    def select_table(self, sql: str, isCamel=True):
        try:
            conn = mysql_connection()
            if conn:
                cursor = conn.cursor()
                cursor.execute(sql)
                desc = cursor.description
                if isCamel:
                    filed = to_lower_camel_list([d[0] for d in desc])
                else:
                    filed = [d[0] for d in desc]
                results = cursor.fetchall()
                # 数据封装成字典
                result_list = [dict(zip(filed, result)) for result in results]
                # 数据封装成Json
                result_json = json.dumps(result_list)
                return result_json
        except Exception as e:
            print(e)
        finally:
            if conn:
                conn.close()



"""
    传入 --table=需要查询的表名
"""
if __name__ == '__main__':
    if (len(sys.argv) == 2 and sys.argv[1].count("--table") == 1 and sys.argv[1][7] == "="):
        table = sys.argv[1][8:]
        sql = f"select * from {table}"
        select_table = selectTable()
        data = select_table.select_table(sql)
        print(data)
        file_str_io("D:/123.txt", data)

